import Router from '@koa/router';
import { BeError, BeSuccess } from '../utils/response';
import { AddUser, DeleteUserList, GetUserList } from '../services/palaceUser';
import { getUserInfo, getUsereExtInfo } from '../thirdServices/palaceApi';
import log from '../utils/log';

const router = new Router();

// 用户列表
router.get('/list', async function (ctx) {
  const { page, phoneNumber } = ctx.query;
  try {
    const data = await GetUserList(page, phoneNumber);
    ctx.body = BeSuccess(data);
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

// 添加用户
router.post('/add', async function (ctx) {
  const { content } = ctx.request.body;
  try {
    const strList = content.split('\n');
    const tokenStr = strList.find(str => str.includes('access-token'));
    const token = tokenStr.split(':')[1].trim();

    const mpDeviceTokenStr = strList.find(str => str.includes('mpDeviceToken'));
    const mpDeviceToken = mpDeviceTokenStr ? mpDeviceTokenStr.split(':')[1].trim() : '';
    const params = {
      merchantId: 2655,
      merchantInfoId: 2655
    };
  
    const res = await getUserInfo(token, params);
    const extRes = await getUsereExtInfo(token, params);
    let openId = '';
    if (extRes.data.status === 200) {
      openId = extRes.data.data.openId;
    }
    if (res.data.code === 200) {
      const userInfo = res.data.data;
      log.debug('【故宫】：添加用户');
      await AddUser(userInfo.id, userInfo.realName || userInfo.phone, userInfo.nickName, userInfo.phoneShow, token, mpDeviceToken, openId);
    }
    ctx.body = BeSuccess('url');
  } catch (error) {
    ctx.body = BeError(error.message);
  }
});

router.post('/del', async function (ctx) {
  const { uuid } = ctx.request.body;
  if (!uuid) {
    throw new Error('uuid为空');
  }

  try {
    const data = await DeleteUserList(uuid);
    ctx.body = BeSuccess(data);
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message, 400);
  }
});

export default router.routes();
